<template>
  <el-dialog v-model="dialogVisible" class="center" title="补货" width="400px" draggable>
    <el-form ref="ruleFormRef" :model="supplyRef" :rules="rules" label-width="100px">
      <el-form-item label="补货数量" prop="count">
        <el-input v-model="supplyRef.count" type="number" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="handleReset">重置</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { Warehouse } from "@/api/interface";
import { FormInstance, ElMessage } from "element-plus";

const supplyRef = ref({ count: "0" });

const validateCount = (rule: any, value: any, callback: any) => {
  const totalHold = dialogProps.value.row.totalHold ?? 0;
  const maxHold = dialogProps.value.row.maxHold ?? 0;
  if (value > maxHold - totalHold) {
    callback(new Error("补货后库存不能超过最大值"));
  } else {
    callback();
  }
};

const rules = reactive({
  count: [
    { required: true, message: "请填写补货数量" },
    { validator: validateCount, trigger: "blur" }
  ]
});

// 提交数据（补货数量）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) {
      return;
    }
    try {
      const count = parseFloat(supplyRef.value.count);
      if (isNaN(count)) {
        throw new Error("请输入有效的补货数量");
      }
      if (!count) {
        throw new Error("补货数量不能为0");
      }
      await dialogProps.value.api!({
        warehouseId: dialogProps.value.row.warehouseId,
        inventoryId: dialogProps.value.row.inventoryId,
        goodsId: dialogProps.value.row.goodsId,
        goodsName: dialogProps.value.row.goodsName,
        measureUnit: dialogProps.value.row.measureUnit,
        count: count
      });
      ElMessage.success({ message: `补货成功` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error: any) {
      console.log(error);
      ElMessage.error({ message: error.message });
    }
  });
};

// 重置按钮
const handleReset = () => {
  supplyRef.value.count = "0";
};

interface DialogProps {
  title: string;
  isView: boolean;
  row: Partial<Warehouse.InventoryData>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {}
});
const openDialog = (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
  supplyRef.value.count = "0";
};

defineExpose({ openDialog });
</script>
